<?php

namespace App\Repositories\Criteria\Article;

use App\Repositories\Contracts\CriteriaInterface;
use App\Repositories\Contracts\RepositoryInterface as Repository;
use App\Repositories\Contracts\RepositoryInterface;
use App\Repositories\Criteria\Criteria;

class SearchCriteria extends Criteria
{
    public $filled = [
        'start_time' => '>=',
        'end_time' => '<=',
        'title' => 'like',
        'author_id' => '=',
    ];

    public $where;

    /**
     * Authorid constructor.
     * @param $authorId
     */
    public function __construct($where)
    {
        $this->where = $where;
    }

    /**
     * @param $model
     * @param RepositoryInterface $repository
     * @return mixed
     */
    public function apply($model, Repository $repository)
    {
        $where = [];
        foreach ($this->where as $k => $v){
            if ( isset($this->filled[$k]) && $v ){
                switch ( $k )
                {
                    case 'start_time':
                        $where[] = ['pub_time' , $this->filled[$k], strtotime($v)];
                        break;
                    case 'end_time':
                        $where[] = ['pub_time', $this->filled[$k], strtotime($v)];
                        break;
                    case 'title':
                        $where[] = [$k, $this->filled[$k], '%' . $v . '%'];
                        break;
                    case 'author_id':
                        $where[] = [$k, '=', $v];
                }
            }
        }
        $query = $model->where($where);
        return $query;
    }
}